<template>
<n-grid x-gap="10" :cols="2">
  <n-gi>
    <n-card class="dict-left" :segmented="true" :bordered="false" size="small">
      <template #header>字典列表</template>
      <div class="inquiry">
        <div class="flex">
          <n-input-group>
            <n-input
                v-model:value="pageParams.name"
                clearable
                placeholder="请输入字典名称"
                @keyup.enter="onInquiry"
            />
            <n-button type="primary" ghost @click="onInquiry">查询</n-button>
          </n-input-group>
          <n-button class="ml-10" type="primary" @click="onAdd">新建</n-button>
        </div>
      </div>
      <n-data-table class="mt-10" :columns="columns" :data="dictStore.parentList" :row-key="(row) => row.id"
                    :row-props="(row) => ({
                      style: 'cursor: pointer;',
                      onClick: () => {
                        editDict(row)
                      }
                    })"/>
      <n-pagination class="mt-10" :page="pageParams.pageNum" :page-size="pageParams.pageSize"
                    :page-count="dictStore.pageInfo.totalPage"
                    :on-update:page="changePageSize"
      />
    </n-card>
  </n-gi>
  <n-gi>
    <n-card :segmented="true" :bordered="false" size="small">
      <template #header>{{title}}</template>
      <n-alert type="info">从左侧列表选择一项后，进行编辑</n-alert>
      <div v-if="currentRow !== null" class="edit-content">
        <n-form
            label-placement="left"
            label-width="100">
          <n-form-item label="名称" path="dictName">
            <n-input
                v-model:value="currentRow.dictKey"
                :disabled="!!currentRow.id"
                type="text"
                placeholder="请输入字典名称"
            />
          </n-form-item>
          <n-form-item label="描述" path="remark">
            <n-input v-model:value="currentRow.dictValue" placeholder="请输入字典描述" />
          </n-form-item>
          <n-form-item label="选项" path="childrenList">
            <div class="children-list">
              <n-button type="primary" size="small" ghost @click="onPushShow">新增选项</n-button>
              <n-table class="mt-10">
                <thead>
                <tr>
                  <th>字典值</th>
                  <th>字典值注释</th>
                  <th>排序</th>
                  <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(item, index) in currentRow.childrenList" :key="index">
                  <td>
                    <n-input v-model:value="item.dictKey" placeholder="请输入字典值" />
                  </td>
                  <td>
                    <n-input v-model:value="item.dictValue" placeholder="请输入字典值注释" />
                  </td>
                  <td>
                    <n-input-number v-model:value="item.dictOrder" :show-button="false" placeholder="排序" />
                  </td>
                  <td>
                    <n-button
                        type="error"
                        size="small"
                        ghost
                        @click="onRemoveRow(index)"
                    >
                      删除
                    </n-button>
                  </td>
                </tr>
                </tbody>
              </n-table>
              <n-button class="mt-10" type="primary" size="small" ghost @click="onPushShow">新增选项</n-button>
            </div>
          </n-form-item>
          <n-form-item style="display: flex; justify-content: center">
            <n-button type="primary" size="medium" ghost @click="resetForm">重置</n-button>
            <n-button class="ml-10" type="primary" size="medium" @click="submitForm">保存</n-button>
          </n-form-item>
        </n-form>
      </div>
    </n-card>
  </n-gi>
</n-grid>
</template>

<script setup lang="jsx">
import {
  NGrid,
  NGi,
  NCard,
  NDataTable,
  NPagination,
  NButton,
  NPopconfirm,
  NAlert,
  NForm,
  NFormItem,
  NInputGroup,
  NInput,
  NInputNumber,
  NTable,
  useMessage
} from "naive-ui";
import useDictStore from "@/store/dictionary.js";
import {computed, onBeforeMount, ref} from "vue";
import {reqDictChildrenList, reqDictDel, reqDictSave} from "@/api/index.js";
import {pageNumByDel} from "@/util/page.js";

const message = useMessage()

const dictStore = useDictStore()
const pageParams = ref({
  pageNum: 1,
  pageSize: 12,
  name: '',
})
const currentRow = ref(null)

const columns = [
  {
    title: '名称',
    key: 'dictKey',
    width: 200,
  },
  {
    title: '描述',
    key: 'dictValue',
    width: 200,
  },
  {
    title: '操作',
    align: 'center',
    key: 'action',
    render(row) {
      return <NPopconfirm
              onPositiveClick={
                () => deleteDict(row.id)
              }
              vSlots={{
                trigger: () => <NButton onClick={(e) => e.stopPropagation()}>删除</NButton>
              }}
          >
            是否删除字典
          </NPopconfirm>
    }
  }
]

const title = computed(() => {
  return currentRow.value !== null ?
      currentRow.value.id !== undefined && currentRow.value.id !== null ?  '编辑字典' : '新建字典'
      : '新建/编辑字典'
})

function onInquiry() {
  dictStore.loadParentList(pageParams.value)
}

function onAdd() {
  currentRow.value = {
    dictKey: '',
    dictValue: '',
    childrenList: [],
  }
}

function onRemoveRow(index) {
  currentRow.value.childrenList.splice(index, 1)
}

function onPushShow() {
  currentRow.value.childrenList.push({
    dictKey: '',
    dictValue: '',
    dictOrder: 0,
  })
}

async function submitForm() {
  await reqDictSave(currentRow.value).then(() => {
    message.success('保存成功')
  })
  await dictStore.loadParentList(pageParams.value)
}

function resetForm() {
  if (currentRow.value.id !== undefined) {
    let row = dictStore.parentList.filter((row) => row.id === currentRow.value.id)[0]
    editDict(row)
  } else {
    onAdd()
  }
}

async function deleteDict(id) {
  await reqDictDel(id)
  pageParams.value.pageNum = pageNumByDel(dictStore.parentList.length, pageParams.value.pageNum)
  await dictStore.loadParentList(pageParams.value)
}

async function editDict(row) {
  const res = await reqDictChildrenList(row.id)
  currentRow.value = {...row, childrenList: res.data}
}

function changePageSize(page) {
  pageParams.value.pageNum = page
  dictStore.loadParentList(pageParams.value)
}

onBeforeMount(() => {
  dictStore.loadParentList(pageParams.value)
})
</script>

<style scoped lang="scss">
.dict-left {
  .inquiry {
    max-width: 400px;
  }
}
.edit-content {
  margin: 15px 20px 0 0;
  .children-list {
    width: 100%;
  }
}
</style>